package com.controller;

import com.entity.Comments;
import com.entity.Lyrics;
import com.entity.Music;
import com.service.MusicService;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Data // 自动生成 set,get,toString 方法
@RestController // 声明为 RestController 配置文件
@RequestMapping("music") // 请求地址
@CrossOrigin // 跨域运行
public class MusicController {
    @Autowired // 自动装配
    private MusicService musicService; // 注入接口

    private Result success(Object data) {
        return new Result(200, data);
    }

    private Result success(String msg) {
        return new Result(200, msg);
    }

    private Result fail(String msg) {
        return new Result(500, msg);
    }

    // 查询所有音乐
    @GetMapping
    public Result selectAllSongs() {
        List<Music> musics = musicService.selectAllSongs();
        LoggerUtil.appendLog("hedgehogcat", "学习站被访问了");
        return musics != null && !musics.isEmpty() ? success(musics) : fail("无查询到数据");
    }

    // id 查询音乐
    @GetMapping("{id}")
    public Result selectOneSongById(@PathVariable String id) {
        Music music = musicService.selectOneSongById(Integer.parseInt(id));
        // 用来记录歌曲日志的请求
        String log = "songId：" + music.getId() + "，SongName：" + music.getSrc().replace(".mp3", "");
        LoggerUtil.appendLog(log, "播放了");
        return music != null ? success(music) : fail("无查询到数据");
    }

    // id 查询歌词
    @GetMapping("lyrics/{LyricsId}")
    public Result selectLyricsById(@PathVariable String LyricsId) {
        Lyrics lyrics = musicService.selectLyricsById(Integer.parseInt(LyricsId));
        return lyrics != null ? success(lyrics) : fail("无查询到数据");
    }

    // 新增评论
    @PostMapping("comments")
    public Result insertComments(@RequestBody Comments comments) {
        int i = musicService.insertComments(comments);
        String log = "songId：" + comments.getSongId() + "，评论姓名：" + comments.getCommenterName() + ", 评论内容：" + comments.getContent();
        LoggerUtil.appendLog(log, "评论了");
        return i > 0 ? success("评论成功") : fail("评论失败");
    }

    // 查询评论信息
    @GetMapping("comments/{id}")
    public Result selectAllCommentsById(@PathVariable String id) {
        List<Comments> comments = musicService.selectAllCommentsById(Integer.parseInt(id));
        LoggerUtil.appendLog(id, "查询了评论");
        return comments != null && !comments.isEmpty() ? success(comments) : fail("无查询到数据");
    }
}
